/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-06-17 23:21:56
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-06-19 16:48:36
 * @FilePath: /lesson42/2.tcp/TcpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstdlib>
#include <string>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;

void Usage(const string &proc)
{
    cout << "\n\rUsage: " << proc << " serverip serverport\n"
         << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));

    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (1)
    {
        bool isconnect = false;
        int cnt = 5;
        int sockfd;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cerr << "create sockfd error" << endl;
            return 1;
        }
        do
        {
            // tcp客户端需要绑定！！！！不需要显式的bind！操作系统来随机端口bind！
            // 客户端进行connect的时候进行bind
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isconnect = true;
                cerr << "connect error, connect: " << cnt << endl;
                cnt--;
                sleep(1);
            }
            else
            {
                break;
            }
        } while (cnt && isconnect);

        if (cnt == 0)
        {
            cerr << "user offline..." << endl;
            break;
        }

        string msg;
        cout << "Please Enter:";
        getline(cin, msg);

        int n = write(sockfd, msg.c_str(), msg.size());
        if (n < 0)
        {
            cerr << "write error" << endl;
            continue;
        }

        char inbuffer[4096];
        n = read(sockfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }
        close(sockfd);
    }

    return 0;
}